// 数据显示不全问题修复脚本
const axios = require('axios');

// API基础地址
const API_BASE_URL = 'http://localhost:5000';

// 测试数据字典API
async function testDataDictionaryAPIs() {
    console.log('🔍 开始测试数据字典API...\n');

    const apis = [
        {
            name: '供应商等级',
            url: `${API_BASE_URL}/api/BusinessPartnerLevel`,
            key: 'levels'
        },
        {
            name: '供应商类别',
            url: `${API_BASE_URL}/api/BusinessPartnerCategory`,
            key: 'categories'
        },
        {
            name: '业务性质',
            url: `${API_BASE_URL}/api/BusinessNature`,
            key: 'natures'
        },
        {
            name: '行业',
            url: `${API_BASE_URL}/api/Industry`,
            key: 'industries'
        },
        {
            name: '地区',
            url: `${API_BASE_URL}/api/Location`,
            key: 'locations'
        },
        {
            name: '人员',
            url: `${API_BASE_URL}/api/Person`,
            key: 'persons'
        }
    ];

    const results = {};

    for (const api of apis) {
        try {
            console.log(`📡 测试 ${api.name}...`);

            const response = await axios.get(api.url, {
                timeout: 10000,
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.status === 200) {
                const data = response.data;
                results[api.key] = {
                    success: true,
                    data: data.data || data.Data || data,
                    count: (data.data || data.Data || data) ? (data.data || data.Data || data).length : 0
                };

                console.log(`✅ ${api.name} - 成功 (${results[api.key].count} 条)`);

                if (results[api.key].count > 0) {
                    console.log(`   示例数据:`, results[api.key].data[0]);
                }
            } else {
                console.log(`❌ ${api.name} - 状态码: ${response.status}`);
                results[api.key] = { success: false, error: `状态码: ${response.status}` };
            }
        } catch (error) {
            console.log(`❌ ${api.name} - 失败: ${error.message}`);
            results[api.key] = { success: false, error: error.message };
        }
        console.log('');
    }

    return results;
}

// 测试供应商列表API
async function testSupplierListAPI() {
    console.log('📋 测试供应商列表API...\n');

    try {
        const response = await axios.get(`${API_BASE_URL}/api/Supplier/list`, {
            params: {
                PageIndex: 1,
                PageSize: 10
            },
            timeout: 10000,
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            const data = response.data;
            const suppliers = data.data || data.Data || [];

            console.log(`✅ 供应商列表 - 成功 (${suppliers.length} 条)`);

            if (suppliers.length > 0) {
                console.log('   供应商数据结构:', Object.keys(suppliers[0]));
                console.log('   示例供应商数据:', suppliers[0]);

                // 分析字段映射问题
                const supplier = suppliers[0];
                console.log('\n🔍 字段映射分析:');
                console.log(`   供应商等级ID: ${supplier.supplierLevelId} -> 名称: ${supplier.supplierLevelName || '未设置'}`);
                console.log(`   供应商类别ID: ${supplier.supplierCategoryId} -> 名称: ${supplier.supplierCategoryName || '未设置'}`);
                console.log(`   行业ID: ${supplier.industryId} -> 名称: ${supplier.industryName || '未设置'}`);
                console.log(`   地区ID: ${supplier.locationId} -> 名称: ${supplier.locationName || '未设置'}`);
                console.log(`   采购人员ID: ${supplier.purchaseRepresentativeId} -> 名称: ${supplier.purchaseRepresentativeName || '未指定'}`);
            }

            return { success: true, data: suppliers };
        } else {
            console.log(`❌ 供应商列表 - 状态码: ${response.status}`);
            return { success: false, error: `状态码: ${response.status}` };
        }
    } catch (error) {
        console.log(`❌ 供应商列表 - 失败: ${error.message}`);
        return { success: false, error: error.message };
    }
}

// 生成修复建议
function generateFixSuggestions(dataDictResults, supplierResults) {
    console.log('\n💡 修复建议:\n');

    const suggestions = [];

    // 检查数据字典是否正常
    const dataDictSuccess = Object.values(dataDictResults).filter(r => r.success).length;
    const dataDictTotal = Object.keys(dataDictResults).length;

    if (dataDictSuccess < dataDictTotal) {
        suggestions.push('❌ 数据字典API存在问题，需要检查后端服务');
        suggestions.push('   建议检查以下API是否正常:');
        Object.entries(dataDictResults).forEach(([key, result]) => {
            if (!result.success) {
                suggestions.push(`   - ${key}: ${result.error}`);
            }
        });
    } else {
        suggestions.push('✅ 数据字典API正常');
    }

    // 检查供应商数据
    if (supplierResults.success && supplierResults.data.length > 0) {
        const supplier = supplierResults.data[0];
        const missingFields = [];

        if (!supplier.supplierLevelName) missingFields.push('供应商等级');
        if (!supplier.supplierCategoryName) missingFields.push('供应商类别');
        if (!supplier.industryName) missingFields.push('所属行业');
        if (!supplier.locationName) missingFields.push('所在地区');
        if (!supplier.purchaseRepresentativeName) missingFields.push('采购人员');

        if (missingFields.length > 0) {
            suggestions.push('❌ 供应商数据缺少关联字段名称');
            suggestions.push('   缺少的字段:', missingFields.join(', '));
            suggestions.push('   解决方案:');
            suggestions.push('   1. 检查后端是否在查询时关联了相关表');
            suggestions.push('   2. 检查前端是否正确映射了数据字典');
            suggestions.push('   3. 确保数据库中有相应的关联数据');
        } else {
            suggestions.push('✅ 供应商数据字段完整');
        }
    } else {
        suggestions.push('❌ 无法获取供应商数据');
        suggestions.push('   建议检查供应商列表API是否正常');
    }

    // 前端修复建议
    suggestions.push('\n🔧 前端修复建议:');
    suggestions.push('1. 确保在组件挂载时先加载数据字典');
    suggestions.push('2. 在显示供应商数据时使用数据字典进行字段映射');
    suggestions.push('3. 添加错误处理和加载状态');
    suggestions.push('4. 使用调试信息显示数据字典加载状态');

    return suggestions;
}

// 主函数
async function main() {
    console.log('🚀 开始诊断数据显示不全问题...\n');
    console.log(`📍 目标地址: ${API_BASE_URL}\n`);

    try {
        // 测试数据字典API
        const dataDictResults = await testDataDictionaryAPIs();

        console.log('='.repeat(50) + '\n');

        // 测试供应商列表API
        const supplierResults = await testSupplierListAPI();

        console.log('='.repeat(50) + '\n');

        // 生成修复建议
        const suggestions = generateFixSuggestions(dataDictResults, supplierResults);
        suggestions.forEach(suggestion => console.log(suggestion));

    } catch (error) {
        console.error('诊断过程中发生错误:', error);
    }

    console.log('\n🏁 诊断完成');
}

// 运行诊断
if (require.main === module) {
    main().catch(console.error);
}

module.exports = {
    testDataDictionaryAPIs,
    testSupplierListAPI,
    generateFixSuggestions
}; 